<template>
  <div>
    <!-- 条件查询 -->
    <div class="block">
      <span class="demonstration">砍价状态</span>
      <el-select v-model="searchEntity.status" placeholder="请选择">
        <el-option label="请选择" value=""></el-option>
        <el-option label="关闭" :value="1"></el-option>
        <el-option label="开启" :value="0"> </el-option>
      </el-select>
      &emsp;&emsp;&emsp;
      <span class="demonstration">商品搜索:</span>
      <el-input placeholder="请输入商品名称/ID" style="width: 250px" v-model="searchEntity.msg"></el-input>
      <el-button type="primary" round @click="getBargainGoodsList()">查询</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="bargaingGoodsList" style="width: 100%" row-key="id" border lazy
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="id" label="ID"> </el-table-column>
      <el-table-column prop="imgUrl" label="秒杀图片">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.imgUrl"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="砍价名称"> </el-table-column>
      <el-table-column prop="bargainPrice" label="砍价价格"> </el-table-column>
      <el-table-column prop="minPrice" label="最低价"> </el-table-column>
      <el-table-column prop="joinNum" label="参与人数"> </el-table-column>
      <el-table-column prop="helpPersonNum" label="帮忙砍价人数">
      </el-table-column>
      <el-table-column prop="successNum" label="砍价成功人数">
      </el-table-column>
      <el-table-column prop="limitNum" label="限量"> </el-table-column>
      <el-table-column prop="residueNum" label="限量剩余"> </el-table-column>
      <el-table-column prop="endTime" value-format="yyyy-MM-dd hh:mm:ss" label="结束时间"></el-table-column>
      <el-table-column label="砍价状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="rgba(67, 129, 230, 1)" inactive-color="#ff4949"
            :active-value="0" :inactive-value="1" @change="changeStatus($event, scope.row, scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="updateCategory(scope.row.id)" type="text" size="small">编辑</el-button>
          <el-button type="text" v-if="scope.row.children == null" size="small" @click="deleteById(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block">
      <el-pagination @size-change="reloadList(num)" @current-change="reloadList(num)"
        :current-page.sync="searchEntity.page" :page-sizes="[10, 20, 30, 40]" :page-size.sync="searchEntity.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 修改Form -->
    <el-dialog title="编辑数据" :rules="rules" :visible.sync="dialogFormVisible">
      <el-form :model="bargaingGoods" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="商品图片" prop="imgUrl">
          <el-upload class="avatar-uploader" action="http://localhost:8001/coco/third/oss/uploadImg"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar" style="width: 200px" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="秒杀名称" prop="title">
          <el-input v-model="bargaingGoods.title"></el-input>
        </el-form-item>
        <el-form-item label="最低价" prop="minPrice">
          <el-input-number v-model="bargaingGoods.minPrice" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="参与人数" prop="joinNum">
          <el-input-number v-model="bargaingGoods.joinNum" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="帮忙砍价人数" prop="helpPersonNum">
          <el-input-number v-model="bargaingGoods.helpPersonNum" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="砍价成功人数" prop="successNum">
          <el-input-number v-model="bargaingGoods.successNum" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="限量" prop="limitNum">
          <el-input-number v-model="bargaingGoods.limitNum" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="限量剩余" prop="residueNum">
          <el-input-number v-model="bargaingGoods.residueNum" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="bargaingGoods.status" active-text="开启" inactive-text="关闭" active-color="#13ce66"
            :active-value="0" :inactive-value="1" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doUpdateDeploy('bargaingGoods')">提交</el-button>
          <el-button @click="dialogFormVisible=false">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data () {
    //这里存放数据
    return {
      token: "",
      bargaingGoods: {},
      bargaingGoodsList: [],
      imgUrl: "",
      searchEntity: {
        limit: 10,
        page: 1,
      },
      total: 0,
      num: 1,
      dialogFormVisible: false,
      rules: {
        name: [
          { required: true, message: "请输入秒杀名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入时间范围", trigger: "blur" }],
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    doUpdateDeploy () {      //修改
      this.$http
        .post("http://localhost:8001/coco/bargain/goods/updateById", this.bargaingGoods, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: "修改配置成功!",
              type: "success",
            });
            this.getBargainGoodsList();
            this.dialogFormVisible = false;
          } else {
            this.$message.error("修改配置失败!");
          }
        })
        .catch((err) => { });
    },
    updateCategory (id) {
      //修改
      // 修改配置
      this.dialogFormVisible = true;
      this.$http
        .get("http://localhost:8001/coco/bargain/goods/findById/" + id, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          console.log(data.data)
          this.bargaingGoods = data.data;
          console.log(this.bargaingGoods);
          this.imgUrl = data.data.imgUrl;
        })
        .catch((err) => { });
    },
    deleteById (id) {
      // 删除
      this.$confirm("此操作将永久删除该秒杀配置, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http
          .delete("http://localhost:8001/coco/bargain/goods/deleteById/" + id, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: "删除商品成功!",
                type: "success",
              });
              this.getBargainGoodsList();
            } else {
              this.$message.error("删除商品失败!");
            }
          })
          .catch((err) => { });
      });
    },
    changeStatus (data, row, index) {
      //修改显示状态
      console.log(data, row, index);
      this.$http
        .put(
          "http://localhost:8001/coco/bargain/goods/updateStatus/" +
          row.id +
          "/" +
          data, {}, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        }
        )
        .then(({ data }) => {
          console.log(data);
          if (data.code == 0) {
            this.$message({
              message: "修改成功!",
              type: "success",
            });
            this.reloadList(this.num);
          } else {
            let newData = b;
            newData.publishStatus = newData.publishStatus == 1 ? "0" : "1";
            this.goodsList[index] = newData;
          }
        })
        .catch((err) => { });
    },
    getBargainGoodsList () {
      //列表
      this.$http
        .post(
          "http://localhost:8001/coco/bargain/goods/findByStatusAndName",
          this.searchEntity, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        }
        )
        .then(({ data }) => {
          console.log(data);
          if (data.code != 0) {
            this.$message({
              message: data.message,
              type: 'error'
            })
            this.$router.push("/");
          }
          this.bargaingGoodsList = data.data.rows;
          this.total = data.data.total;
        })
        .catch((err) => { });
    },
    reloadList (num) {
      //分页
      if (num == 1) {
        this.saleList();
      }
      if (num == 2) {
        this.warehouseList();
      }
      if (num == 3) {
        this.findSelloutGoods();
      }
      if (num == 4) {
        this.findRecycleGoods();
      }
    },
    beforeAvatarUpload (file) {
      //上传前
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess (res, file) {
      //上传成功回调
      console.log(res);
      this.imgUrl = res;
      this.deploy.deployImg = this.imgUrl;
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created () {
    this.token = localStorage.getItem("token");
    this.getBargainGoodsList(); //列表
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () { },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>